const express = require('express')
const router = express.Router()
const {
    getAllOrderList,
    modifyOrderState,
    updateProductSalesAndStore,
    getOrderDetail,
    updateProductListState
} = require('../../model/mongo')

router.get('/list', async (req, res) => {
    let result = {
        code: 200,
        msg: '获取最新订单'
    }
    result.data = await getAllOrderList(0)
    res.send(JSON.stringify(result))
})

router.get('/sendlist', async (req, res) => {
    let result = {
        code: 200,
        msg: '获取已发货订单'
    }
    result.data = await getAllOrderList(1)
    res.send(JSON.stringify(result))
})

router.get('/completelist', async (req, res) => {
    let result = {
        code: 200,
        msg: '获取已完成订单'
    }
    result.data = await getAllOrderList(2)
    res.send(JSON.stringify(result))
})

router.get('/returnlist', async (req, res) => {
    let result = {
        code: 200,
        msg: '获取退货订单'
    }
    result.data = await getAllOrderList(3)
    res.send(JSON.stringify(result))
})

router.put('/send', async (req, res) => {
    const { orderid, msg } = req.body
    let result = {
        code: 200,
        msg: '修改订单状态为已发货'
    }
    result.tip = await modifyOrderState(orderid, 1, msg||'已发货')
    res.send(JSON.stringify(result))
})

router.put('/return', async (req, res) => {
    const { orderid } = req.body
    let result = {
        code: 200,
        msg: '修改订单状态为同意退货'
    }
    try {
        let { proid, count } = await getOrderDetail(orderid)
        result.tip = await modifyOrderState(orderid, 4, '退货成功')
        result.store = await updateProductSalesAndStore(proid, 0 - count)
        await updateProductListState(proid, 'issale', true)
    } catch (err) {
        result.code = 400
        result.tip = '出错了'
    }
    res.send(JSON.stringify(result))
})

router.put('/nostore', async (req, res) => {
    const { orderid } = req.body
    let result = {
        code: 200,
        msg: '修改订单状态为无货'
    }
    try {
        let { proid, count } = await getOrderDetail(orderid)
        result.tip = await modifyOrderState(orderid, 4, '商品无货，退货成功')
        result.store = await updateProductSalesAndStore(proid, 0 - count)
        await updateProductListState(proid, 'issale', false)
    } catch (e) {
        result.code = 400
        result.tip = '出错了'
    }
    res.send(JSON.stringify(result))
})

module.exports = router
